package servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

import ws.GestionFichiersInterfaceWS;
import ws.GestionFichiersInterfaceWSImplService;

/**
 * Servlet implementation class GestionFichiersServlet
 */
@WebServlet("/GestionFichiersServlet")
public class GestionFichiersServlet extends HttpServlet {
	
	//Appel au WebService//
	GestionFichiersInterfaceWSImplService service = new GestionFichiersInterfaceWSImplService();
	GestionFichiersInterfaceWS gestionFichiers = service.getGestionFichiersInterfaceWSImplPort();	
	
	private static final long serialVersionUID = 1L;
	
	private static String RELOAD = "/index.jsp";  //reloader la vue (id 2)
	private static String OPEN = "/open.jsp";     //ouvrir un fichier (id 3)
	private static String DOWNLOAD = "/download.jsp"; //télécharger un fichier sur son poste (id 4)
	private static String RENAME = "/rename.jsp"; //renommer un fichier (id 5)
	private static String REMOVE = "/remove.jsp"; //supprimer un fichier (id 6)
	private static String ERROR = "/error.jsp";   //cas d'erreur
	byte[] temp = null;
	int id;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GestionFichiersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String forward = "";
		try {
	        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
	        for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                if (fieldname.equals("id")){
	                	if (fieldvalue.equals("1")){
	                		id = 1;
	                		System.out.println("Passé ici");
	                	}else{
	                		if (fieldvalue.equals("3")){
	                			id = 3;
	                			forward = OPEN;
	                		}else{
	        					if (fieldvalue.equals("4")){
	        						id = 4;
	        						forward = DOWNLOAD;
	        					}else{
	        						if (fieldvalue.equals("5")){
	        							id = 5;
	        							forward = RENAME;
	        						}else{
	        							if (fieldvalue.equals("6")){
	        								id = 6;
	        								forward = REMOVE;
	        							}else{
	        								id = 7;
	        								forward = ERROR;
	        							}
	        						}
	        					}
	        				}
	                	}
	                }
	         
	            } else {
	            	
	                // Process form file field (input type="file").
	            	
	                String fileName = FilenameUtils.getName(item.getName());
	                InputStream fileContent = item.getInputStream();
	                byte[] contenuFichier = IOUtils.toByteArray(fileContent);
	                byte[] nomDuFichier = fileName.getBytes();
	                
	            	if ( id == 1 ){            	
	            		
	        			gestionFichiers.uploadAFile(contenuFichier, nomDuFichier);
	        			forward = RELOAD;
	        			
	            	}
	            	
	            }
	        }
	        
	    } catch (FileUploadException e) {
	    	
	        throw new ServletException("Cannot parse multipart request.", e);
	        
	    }
	    
		RequestDispatcher view = request.getRequestDispatcher(forward);
		view.forward(request, response);
		
	}

}
